import { ConfigProvider } from 'antd';
import analytics from '@/utils/analytics';
import jurisdiction from '@/utils/jurisdiction';
import { MICRO_CONFIG } from '@/pages/Micro/helper';
import { delay } from 'lodash';

import { globalThemeGroup } from '#/theme';
import emitter from '@/utils/events';

export default {
  namespace: 'global',
  state: {
    collapsed: false, // 菜单展开收起
    isFullScreen: false, // 主项目全屏控制菜单隐藏
    isLargeScreenIn: false, // 是否在大屏子项目中
    theme: {
      key: localStorage.getItem('saas-theme') || 'light',
      enums: {},
    },
  },
  reducers: {
    update(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTheme(state, { payload }) {
      // 主题全局更新使用，使用浏览器缓存
      localStorage.setItem('saas-theme', payload);
      const currentTheme = globalThemeGroup[payload];
      document.body.parentElement.dataset.typeColor = currentTheme.key;

      emitter.emit('onGlobalThemeChange', currentTheme);

      insertStyEnum(currentTheme.enums);
      return {
        ...state,
        theme: {
          ...currentTheme,
        },
      };
    },
    checkTheme(state, { payload }) {
      // 主题临时切换使用，检查当前是否正确
      let themeType = 'light';
      const { menuCode } = payload ?? {};

      // if (menuCode === 'MenuCode') {
      //   // 应用管理，希望有人能拆到micro-configure里去
      //   themeType = 'dark';
      // } else {
      themeType = localStorage.getItem('saas-theme') || 'light';
      // }
      const currentTheme = globalThemeGroup[themeType] || globalThemeGroup['light'];

      document.body.parentElement.dataset.typeColor = currentTheme.key;

      if (menuCode) {
        // 第二次check时进行变量替换
        // if (state.theme.key !== currentTheme.key) {
        //   emitter.emit('onGlobalThemeChange', currentTheme);
        // }
        insertStyEnum(currentTheme.enums);
      }

      return {
        ...state,
        theme: {
          ...currentTheme,
        },
      };
    },
  },
  subscriptions: {
    setup({ history, dispatch }) {
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      return history.listen(({ pathname }) => {
        if (pathname === '/') return;
        const menuItem = jurisdiction.getMenuItem(pathname);
        analytics.onChangePage(pathname, menuItem);
        delay(() => {
          dispatch({
            type: 'checkTheme',
            payload: menuItem,
          });
        }, 10);
      });
    },
  },
};

// 可插入到全局的css变量
export const otherEnums = {
  '--global_HeaderBarHei': '72px',
};
function insertStyEnum(enums = []) {
  if (enums.length === 0) return;
  const enumStr = Object.entries({ ...enums, ...otherEnums })
    .map(([k, v]) => `${k}:${v}`)
    .join(';');
  const htmlDom = window.document.querySelector('html');
  let styStr = htmlDom.getAttribute('style') || '';
  let matchFontSizeStr;
  if (styStr.indexOf('font-size:') > -1) {
    const reg = /font-size:\s*\d+(\.\d+)?(px|em|rem|%);\s*/g;
    const match = styStr.match(reg)?.[0];
    if (match) {
      matchFontSizeStr = match;
    }
  }
  htmlDom.setAttribute('style', `${matchFontSizeStr || ''}${enumStr}`);
  // setAntdTheme(enums);
}

const setAntdTheme = (enums = []) => {
  const currentEnums = {
    '--ant-primaryColor': 'primaryColor',
    '--ant-errorColor': 'errorColor',
    '--ant-warningColor': 'warningColor',
    '--ant-successColor': 'successColor',
    '--ant-infoColor': 'infoColor',
  };

  let theme = {};
  Object.entries(currentEnums).map(([k, v]) => (theme[v] = enums[k]));

  ConfigProvider.config({
    theme,
  });
};
